<?php

namespace SC\Admin\Widgets;

use Closure;


abstract class Panel extends Widget
{
    protected $fields = [];
    protected $title = null;
    protected $actions = [
        'list' => 0,
        'create' => 0,
        'display' => 0,
        'update' => 0,
        'delete' => 0,
    ];
    protected $query = null;

    public function title($title) {
        $this->title = $title;
        return $this;
    }

    public function query(Closure $query) {
        $this->query = $query;
        return $this;
    }

    public function field($name, $class=null)
    {
        $class = $class ?: Support\Field::class;
        $field = new $class($name);
        $this->fields[] = $field;

        return $field;
    }

    public function pk()
    {
        return $this->field('id')->type('pk');
    }

    public function string($name)
    {
        return $this->input($name);
    }

    public function input($name)
    {
        return $this->field($name)->type('input');
    }

    public function number($name)
    {
        return $this->field($name)->type('number');
    }

    public function select($name)
    {
        return $this->field($name, Support\OptionsField::class)->type('select');
    }

    public function image($name)
    {
        return $this->field($name, Support\SizeField::class)->type('image');
    }

    public function html($name)
    {
        \Admin::extJs('<script src="https://cdn.bootcss.com/quill/1.3.6/quill.min.js"></script>');
        \Admin::extCss('<link href="https://cdn.bootcss.com/quill/1.3.6/quill.snow.min.css" rel="stylesheet">');
        \Admin::extJs('<script src="http://cdn.pystarter.com/js/quill-editor.js"></script>');
        \Admin::extJs('<script>Vue.component("quill-editor", QuillEditor)</script>');

        return $this->field($name)->type('html');
    }

    public function fieldsMeta()
    {
        $fieldsMeta = [];
        foreach($this->fields as $field) {
            $fieldsMeta[] = $field->meta();
        }
        return $fieldsMeta;
    }

    public function fieldsValue($payload)
    {
        $fieldsValue = [];
        foreach($this->fields as $field) {
            $fieldsValue[] = $field->value($payload);
        }

        return $fieldsValue;
    }

    public function disableAction(...$actions) {
        foreach($actions as $action) {
            unset($this->actions[$action]);
        }
    }

    public function actions()
    {
        return \array_keys($this->actions);
    }
}